package com.tedu.egsringbootmvc.controller;

import com.tedu.egsringbootmvc.common.result.JsonResult;
import com.tedu.egsringbootmvc.common.result.StatusCode;
import com.tedu.egsringbootmvc.mapper.UserMapper;
import com.tedu.egsringbootmvc.pojo.dto.UserArticleDTO;
import com.tedu.egsringbootmvc.pojo.dto.UserLoginDTO;
import com.tedu.egsringbootmvc.pojo.entity.MvcArticle;
import com.tedu.egsringbootmvc.pojo.entity.MvcUser;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.hibernate.validator.constraints.Range;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpSession;

@Api(tags = "用户模块")
@RestController
@Slf4j
@RequestMapping("/v1/users")
@Validated
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @ApiOperation("用户登录功能")
    @PostMapping("/login")
    public JsonResult login(@RequestBody @Validated UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session){
        log.info("UserController: login");
        log.debug(userLoginDTO.toString());
        MvcUser user = userMapper.selectByUsernameAndPassword(userLoginDTO.getUsername(), userLoginDTO.getPassword());
        if(user == null){
            return new JsonResult(StatusCode.USERNAME_PASSWORD_ERROR);
        }else{
            session.setAttribute("user", user);
            return JsonResult.success();
        }
    }

    @PostMapping("/article")
    @ApiOperation("发表文章功能")
    public JsonResult insertArticle(@RequestBody @Validated UserArticleDTO userArticleDTO,@ApiIgnore HttpSession session){
        log.info("UserController: insertArticle");
        log.debug(userArticleDTO.toString());

        MvcUser user = (MvcUser)session.getAttribute("user");

        MvcArticle article = new MvcArticle();
        BeanUtils.copyProperties(userArticleDTO,article);
        article.setUserId(user.getId());
        userMapper.insertArticle(article);
        return JsonResult.success();
    }

    @ApiOperation("查询指定文章功能")
    @GetMapping("/selectByArticleId")
    @ApiImplicitParam(name = "id",value = "文章ID",required = true,example = "1",dataType = "int")
    public JsonResult selectArticleById(@RequestParam @Range(min = 1,max = 100,message = "文章id只能在1-100之间") int id){
        return JsonResult.success(userMapper.selectArticleById(id));
    }
}
